from odoo import models, api, _
from odoo.osv import expression
from odoo.tools.misc import format_date


class ProductionWIPTwo(models.AbstractModel):
    _name = 's.production.wip.two'
    _description = 'Production WIP'

    @api.model
    def get_station_wip_data(self, domain, product_type='P', search=False):
        if not domain:
            domain = []
        if product_type == 'sample':
            domain = expression.AND([domain, [('product_id.materiel_status', '!=', 'P')]])
        elif product_type == 'mass':
            domain = expression.AND([domain, [('product_id.materiel_status', '=', 'P')]])
        wip_group_data = []
        pnl_total = 0
        seta_total = 0  # 总面积
        outbound_total = 0  # 外发总数量
        outbound_area_total = 0  # 外发总面积
        data = self.env['mrp.workorder.sum'].sudo()._read_group(
            domain,
            ['work_station_id'],
            ['qty_wip_pnl:sum', 'qty_wip_seta:sum', 'outbound_qty_wip_pnl:sum', 'outbound_qty_wip_pnl_area:sum']
        )

        if not search:
            station_ids = self.env['work.station'].search([('disuse', '=', False)])
            for rec in station_ids:
                rec_data = list(filter(lambda x: x[0] == rec, data))
                if rec_data:
                    station, qty_wip_pnl, qty_wip_seta, outbound_qty_wip_pnl, outbound_qty_wip_pnl_area = rec_data[0]
                    qty_wip_pnl = int(qty_wip_pnl)
                    seta_total += round(qty_wip_seta, 2) or 0
                    outbound_total += outbound_qty_wip_pnl or 0
                    pnl_total += qty_wip_pnl or 0
                    wip_group_data.append({
                        'sequence': rec.sequence,
                        'station_id': rec.id,
                        'station_name': rec.name,
                        'qty_wip_pnl': qty_wip_pnl or 0,
                        'qty_wip_seta': round(qty_wip_seta, 2) or 0,
                        'outbound_qty_wip_pnl_area': round(outbound_qty_wip_pnl_area, 2) or 0,
                        'outbound_qty_wip_pnl': outbound_qty_wip_pnl or 0
                    })
                else:
                    wip_group_data.append({
                        'sequence': rec.sequence,
                        'station_id': rec.id,
                        'station_name': rec.name,
                        'qty_wip_pnl': 0,
                        'qty_wip_seta': 0,
                        'outbound_qty_wip_pnl': 0
                    })
        else:
            for station, qty_wip_pnl, qty_wip_seta, outbound_qty_wip_pnl, outbound_qty_wip_pnl_area in data:
                pnl_total += int(qty_wip_pnl) or 0
                seta_total += round(qty_wip_seta, 2) or 0
                outbound_area_total += round(qty_wip_seta, 2) or 0
                outbound_total += outbound_qty_wip_pnl or 0
                wip_group_data.append({
                    'sequence': station.sequence,
                    'station_id': station.id,
                    'station_name': station.name,
                    'qty_wip_pnl': qty_wip_pnl or 0,
                    'qty_wip_seta': round(qty_wip_seta, 2) or 0,
                    'outbound_qty_wip_pnl': outbound_qty_wip_pnl or 0,
                    'outbound_qty_wip_pnl_area': round(outbound_qty_wip_pnl_area, 2) or 0,
                })
            wip_group_data.sort(key=lambda x: x.get('sequence', 100))
        return {
            'wip_group_data': wip_group_data,
            'pnl_total': pnl_total,
            'seta_total': seta_total,
            'outbound_total': outbound_total,
            'outbound_area_total': outbound_area_total
        }

    @api.model
    def get_station_wip_line_data(self, station_id, domain, product_type='P'):
        if not domain:
            domain = []
        domain = expression.AND([
            domain,
            [('work_station_id', '=', station_id)],
        ])

        if product_type == 'sample':
            domain = expression.AND([domain, [('product_id.materiel_status', '!=', 'P')]])
        elif product_type == 'mass':
            domain = expression.AND([domain, [('product_id.materiel_status', '=', 'P')]])
        wip_line_data = []
        if not station_id:
            return wip_line_data
        for line in self.env['mrp.workorder.sum'].sudo().search(domain):
            if not line.production_id:
                continue
            sources = line.production_id._get_all_sources() + line.production_id
            planned_receiving_date = ''
            order_qty = 0
            sale_line_ids = sources.mapped('s_sale_order_line_ids')
            rd_line_ids = sources.mapped('s_development_line_ids')
            if sale_line_ids:
                rec = sale_line_ids.filtered(lambda x: x.s_planned_receiving_date)
                if rec:
                    planned_receiving_date = min(rec.mapped('s_planned_receiving_date'))
                order_qty = sum(sale_line_ids.mapped('product_uom_qty'))
            elif rd_line_ids:
                planned_receiving_date = rd_line_ids[0].order_id.planned_receiving_date
                order_qty = sum(rd_line_ids.mapped('product_qty'))
            work_order_ids = line.production_id.workorder_ids.filtered(lambda x: x.state != 'done').sorted('step')
            if work_order_ids:
                center = work_order_ids[0].workcenter_id.display_name
                stop_time = work_order_ids[0].s_stop_time
            else:
                center = ''
                stop_time = 0
            wip_line_data.append({
                'line_id': line.id,
                'product_name': line.product_id.name,
                'production_name': line.production_id.name,
                'state': _('pause') if line.production_id.is_lock else _('progress'),
                'online_process': center,
                'planned_receiving_date': planned_receiving_date and f'{format_date(self.env, planned_receiving_date)}' or '',
                'order_qty': int(order_qty),
                'stop_time': int(stop_time),
                'qty_wip': line.qty_wip or 0,
                'qty_wip_set': line.qty_wip_set or 0,
                'qty_wip_pnl': line.qty_wip_pnl or 0,
                'outbound_qty_wip_pnl': line.outbound_qty_wip_pnl or 0,
                'qty_wip_seta': round(line.qty_wip_seta, 3) or 0,
                'pnl_size': line.pnl_size
            })
        wip_line_data = sorted(wip_line_data, key=lambda x: x['stop_time'], reverse=True)
        return wip_line_data